package com.tgpms.web.earlierStage.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.tgpms.auth.security.TokenService;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.exception.InsertException;
import com.tgpms.util.Common;
import com.tgpms.util.FTPUtil;
import com.tgpms.web.earlierStage.entity.DocUploadEntity;
import com.tgpms.web.earlierStage.service.EalierDocUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "EalierDocUploadController", tags = "前期 文档实体信息相关接口")
@RestController
@RequestMapping(value = "/ev/earlierDocUpload")
@CrossOrigin//此注解解决可能的跨域问题
public class EalierDocUploadController {
	
	private final Logger log = LoggerFactory.getLogger(EalierDocUploadController.class);

	@Autowired
	private EalierDocUploadService ealierDocUploadService;
	@Autowired
	private TokenService tokenService;
	//ftp_url
	@Value("${ftpparam.url}")
	private String url;
	@Value("${ftpparam.port}")
	private Integer port;
	@Value("${ftpparam.username}")
	private String username;
	@Value("${ftpparam.password}")
	private String password;
	@Value("${ftpparam.downurl}")
	private String downurl;
	@Value("${ftpparam.filepath3}")
	private String filepath3;
	@Value("${ftpparam.localloadfile}")
	private String localloadfile;

	@ApiOperation(value = "新增文档实体信息接口", notes = "新增文档实体信息接口", httpMethod = "POST")
	@PostMapping(value = "/addDocUpload",headers = "content-type=multipart/form-data")
	public Result addDocUpload(@RequestParam(required = false) String projectId,
			@RequestParam(required = false) String taskId,
			@RequestParam(required = false) String sortId,
			@RequestParam(required = false) String docName,
			@RequestParam(required = false) String fruitYn,
			HttpServletRequest request,@RequestParam MultipartFile file) {
		log.info("======新增文档实体信息接口开始");
		Result result = new Result();
		if(Common.isEmpty(projectId) || Common.isEmpty(taskId)
				|| Common.isEmpty(docName) || Common.isEmpty(file)
				|| Common.isEmpty(fruitYn) ) {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain());
			return result;
		}
		try {
			DocUploadEntity docUpload = new DocUploadEntity();
			docUpload.setProjectId(projectId);
			docUpload.setTaskId(taskId);
			docUpload.setSortId(sortId);
			docUpload.setFruitYn(fruitYn);
			//获取文件大小
			Long fileSize = file.getSize();
			docUpload.setFileSize(fileSize);
			//获取上传人
			String insertName = tokenService.getUserName(request);
			docUpload.setUploadUser(insertName);
			//指定存放上传文件的临时目录
			String fileDir = localloadfile;
			File dir = new File(fileDir);
			//判断目录是否存在，不存在则创建目录
			if (!dir.exists()){
				dir.mkdirs();
			}
			//处理中文文件名乱码
			docUpload.setDocName(docName);
//			docUpload.setDocName(Common.getUTFStringByEncoding(docName));
			// 获取文件后缀
			String suffix=(docName.substring(docName.lastIndexOf(".")+1)).toLowerCase();
			String newfileName = "qqgl"+Common.fromDateFormat("yyyyMMddHHmmssSSS");
			docName = newfileName+"."+suffix;
			docUpload.setNewDocName(docName);
			File excelFile = new File(dir.getAbsolutePath()+ File.separator+ docName);
			file.transferTo(excelFile);
//			if(!suffix.equals("pdf")) {
//				//读取文件内容
//				reader = new FileReader(excelFile);//定义一个fileReader对象，用来初始化BufferedReader
//				bReader = new BufferedReader(reader);//new一个BufferedReader对象，将文件内容读取到缓存
//				sb = new StringBuilder();//定义一个字符串缓存，将字符串存放缓存中
//				String s = "";
//				while ((s =bReader.readLine()) != null) {//逐行读取文件内容，不读取换行符和末尾的空格
//					sb.append(s);//将读取的字符串添加换行符后累加存放在缓存中
//				}
//				docUpload.setDocContext(sb.toString());
//			}
			docUpload.setDocContext(docName);
			docUpload.setFilePath(filepath3);
			result = ealierDocUploadService.addDocUpload(docUpload, result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_INSERT.getExplain());
		} finally {
			
		}
	}


	@ApiOperation(value = "下载文档实体信息接口", notes = "下载文档实体信息接口", httpMethod = "POST")
	@PostMapping(value = "/downDocUpload")
	public ResponseEntity<byte[]> downDocUpload(@RequestParam(value = "id", required = true) String id,HttpServletRequest request) {
		ResponseEntity<byte[]> entity = null;
		InputStream in = null;
		try {
			DocUploadEntity docUpload = ealierDocUploadService.selDocUploadById(id);
			//先从本地文件夹取文件，有则本地下载，无则ftp下载
			String fileDir = localloadfile;
			File dir = new File(fileDir);
			if (!dir.exists()){
				dir.mkdirs();
				in = FTPUtil.downloadFileForIn(url, port, username, password, docUpload.getFilePath(), docUpload.getNewDocName());
			}else {
				File excelFile = new File(dir.getAbsolutePath()+ File.separator+ docUpload.getNewDocName());
				if(excelFile.exists()) {
					in = new FileInputStream(excelFile);
				}else {
					in = FTPUtil.downloadFileForIn(url, port, username, password, docUpload.getFilePath(), docUpload.getNewDocName());
				}
			}
			//设置浏览器响应
			HttpHeaders headers = new HttpHeaders();
			headers.setContentDispositionFormData("attachment", docUpload.getDocName());
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			HttpStatus status = HttpStatus.OK;
			//返回字节流IOUtils.toByteArray(in)
			entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, status);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(in!=null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return entity;
	}
	
	
	@DeleteMapping(value = "/deleteDocUpload")
	public Result deleteDocUpload(@RequestParam(value = "id", required = true) String id,HttpServletRequest request) {
		Result result = new Result();
		if(Common.isEmpty(id)) {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain()+"|主键为空");
			return result;
		}
		try {
			result = ealierDocUploadService.deleteDocUpload(id, result);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_DELETE.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_DELETE.getExplain());
		}
		return result;
	}

	@ApiOperation(value = "修改文档实体", notes = "修改文档实体", httpMethod = "PUT")
	@PutMapping(value = "/updateDocUpload")
	public Result updateDocUpload(@RequestBody DocUploadEntity docUploadEntity,HttpServletRequest request) {
		Result result = new Result();
		if(Common.isEmpty(docUploadEntity.getId())) {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain()+"|主键为空");
			return result;
		}
		try {
			String insertName = tokenService.getUserName(request);
			docUploadEntity.setModifyUser(insertName);
			result = ealierDocUploadService.updateDocUpload(docUploadEntity, result);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
		}
		return result;
	}

}
